package cn.edu.cqu.zhihucrawler2.fragment;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.util.ArrayMap;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import cn.edu.cqu.zhihucrawler2.R;
import cn.edu.cqu.zhihucrawler2.commen.BitmapUtil;
import cn.edu.cqu.zhihucrawler2.commen.CommenValue;
import cn.edu.cqu.zhihucrawler2.commen.LoadMoreListView;


/**
 * A placeholder fragment containing a simple view.
 */
public class ArticleFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, LoadMoreListView.OnLoadMore
{
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";
    private SearchTask mAuthTask = null;
    private LoadMoreListView listView_answer;
    private SwipeRefreshLayout swip;
    private SimpleAdapter adapter;
    private int page = 0;
    private View mProgressView, mContentView;

    private List<Map<String, Object>> inputArticleURL = new LinkedList<>();

    public ArticleFragment()
    {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static ArticleFragment newInstance(int sectionNumber)
    {
        ArticleFragment fragment = new ArticleFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        View rootView = inflater.inflate(R.layout.fragment_article, container, false);
        mProgressView = rootView.findViewById(R.id.show_progress);
        mContentView = rootView.findViewById(R.id.show_content);

        initView(rootView);
        initData(page++);
        return rootView;
    }

    private void initView(View rootView)
    {
        listView_answer = (LoadMoreListView) rootView.findViewById(R.id.listView_answer);
        listView_answer.setLoadMoreListen(this);
        swip = (SwipeRefreshLayout) rootView.findViewById(R.id.swip_index);
        swip.setOnRefreshListener(this);
        swip.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light,
                android.R.color.holo_green_light);
        adapter = new SimpleAdapter(getContext(), inputArticleURL, R.layout.article_layout,
                new String[]{"title", "content", "likeCount", "topic", "imgSrc"},
                new int[]{R.id.textView_title, R.id.textView_content, R.id.textView_likeCount, R.id.textView_topic, R.id.ImageView});
        adapter.setViewBinder(new SimpleAdapter.ViewBinder()
        {
            @Override
            public boolean setViewValue(View view, Object data, String s)
            {
                if (view instanceof ImageView && data instanceof Bitmap) {
                    ImageView iv = (ImageView) view;
                    iv.setImageBitmap((Bitmap) data);
                    return true;
                }
                return false;
            }
        });
        listView_answer.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
            {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                Uri content_url = Uri.parse(inputArticleURL.get(i).get("url").toString());
                intent.setData(content_url);
                startActivity(intent);
            }
        });
        listView_answer.setAdapter(adapter);
    }
    /**
     * 加载数据
     * @param pageNo 页数
     */
    private void initData(int pageNo) {
        LinkedList<Map.Entry<String, String>> topicURL = CommenValue.articleURL;
        mAuthTask = new SearchTask(getContext(),topicURL.get(pageNo));
        mAuthTask.execute();
    }

    @Override
    public void onRefresh()
    {
        if(getUserVisibleHint())
            Toast.makeText(getActivity(), "开始刷新", Toast.LENGTH_SHORT).show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if(swip.isShown()){
                    swip.setRefreshing(false);
                }
                if(getUserVisibleHint())
                    Toast.makeText(getActivity(), "刷新完成", Toast.LENGTH_SHORT).show();
            }
        }, 3000);
    }

    @Override
    public void loadMore()
    {
        if(page >= inputArticleURL.size())
        {
            if(getUserVisibleHint())
            {
                Toast.makeText(getActivity(), "已经是最后一页了", Toast.LENGTH_SHORT).show();
                listView_answer.onLoadComplete();
            }
            return;
        }
        else
        {
            initData(page);
            page++;
        }
    }

    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mContentView.setVisibility(show ? View.GONE : View.VISIBLE);
            mContentView.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mContentView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mContentView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    private class SearchTask extends AsyncTask<Void, Void, Boolean>
    {
        Context context;
        Map.Entry<String, String> topicURL;

        SearchTask(Context context, Map.Entry<String, String> topicURL)
        {
            this.context = context;
            this.topicURL = topicURL;
        }

        @Override
        protected Boolean doInBackground(Void... voids)
        {
            Connection conn=Jsoup.connect("https://zhuanlan.zhihu.com/"+ topicURL.getValue());
            Document doc;
            try
            {
                doc = conn.get();
                Elements articleList = doc.select("div[class=PostListItem PostListItem--responsive]");
                for (Element element : articleList)
                {
                    Map<String, Object> map = new ArrayMap<>();
                    //图片
                    String imgSrc = element.select("img").attr("src");
                    map.put("imgSrc", BitmapUtil.getBitmap(imgSrc));
                    //作者 标题
                    String authorName = element.select("a[class=PostListItem-name]").text();
                    String title = element.select("span[class=PostListItem-title]").text();
                    map.put("title", title);
                    //简略内容
                    Elements spanContent = element.select("p[class=PostListItem-summary]");
                    String minContent = spanContent.text();
                    map.put("content", authorName+":"+minContent);
                    //赞数
                    String likeCount = element.select("div[class=PostListItem-footer]").get(0).select("span").get(2).select("a").text();
                    map.put("likeCount", likeCount);
                    //回答URL
                    String url =  element.select("div[class=PostListItem-info]").get(0).select("a").get(0).attr("href");
                    map.put("topic",url);
                    map.put("url","https://zhuanlan.zhihu.com"+url);
                    inputArticleURL.add(map);
                }
            } catch (IOException e)
            {
                e.printStackTrace();
            }
            return inputArticleURL.size() != 0;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            if (success) {
                listView_answer.onLoadComplete();
                adapter.notifyDataSetChanged();
                if(getUserVisibleHint())
                    Toast.makeText(getActivity(), "加载完成", Toast.LENGTH_SHORT).show();
            } else {
                if(getUserVisibleHint())
                    Toast.makeText(getActivity(),"连接服务器出错,请检查网络连接",Toast.LENGTH_SHORT).show();
            }
            mAuthTask = null;
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
        }
    }
}